package com.cll.prototype.email.service.impl;

import com.cll.prototype.api.email.mapper.SendEmailLogMapper;
import com.cll.prototype.common.dictionary.EmailTypeEnum;
import com.cll.prototype.common.dto.AjaxResult;
import com.cll.prototype.api.email.entity.SendEmailLog;
import com.cll.prototype.api.email.service.ISendEmailLogService;
import com.cll.prototype.email.dto.TemplateEmailDto;
import com.cll.prototype.email.service.IEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author CLL
 * @since 2020-10-27
 */
@Service
public class SendEmailLogServiceImpl implements ISendEmailLogService {

    private static final Logger logger = LoggerFactory.getLogger(SendEmailLogServiceImpl.class);

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private SendEmailLogMapper sendEmailLogMapper;

    @Autowired
    private IEmailService emailService;

    @Override
    public AjaxResult sendAndRecord(String to, String subject, String captcha) {
        logger.info("===>>> 发送邮件并记录发送日志");
        HashMap<String, String> param = new HashMap<>(1);
        param.put("code", captcha);
        TemplateEmailDto templateEmailDto = new TemplateEmailDto(EmailTypeEnum.REGISTER.getName(), param);
        AjaxResult ajaxResult = emailService.sendTemplateEmail(null, to, subject, templateEmailDto);
        SendEmailLog sendEmailLog = new SendEmailLog();
        sendEmailLog.setSender(from);
        sendEmailLog.setReceiver(to);
        sendEmailLog.setSubject(subject);
        sendEmailLog.setContent("注册模板");
        sendEmailLog.setType(5);
        sendEmailLog.setResult(ajaxResult.getCode());
        sendEmailLog.setGmtCreate(LocalDateTime.now());
        int insertRecord = sendEmailLogMapper.add(sendEmailLog);
        return 1 == insertRecord ? AjaxResult.success(20, "发送成功", 1) : AjaxResult.error(50, "发送失败");
    }
}
